<?php declare(strict_types=1);

namespace app\home\controller;

use app\common\service\ArticleService;
use app\common\service\CommonService;
use app\common\service\SiteService;
use app\home\Diluma;
use app\Request;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\View;

class Article extends Diluma
{
    // 分页
    protected $defaultConfig = [
        'query'     => [], //url额外参数
        'fragment'  => '', //url锚点
        'var_page'  => 'page', //分页变量
        'list_rows' => 12, //每页数量
    ];
    /**
     * 文章列表
     * @return string
     */
    public function index(Request $request)
    {
        $service = new ArticleService();
        $categoryId = $request->param('category_id', 228, 'intval');
        $childNav = (new SiteService())->getChildNav($categoryId);
        $this->defaultConfig = [
            'query' => $request->param(),
        ];
        $items = $service->getDatas(['category_id' => $categoryId], $this->defaultConfig);
        $recNews = $service->getRecArticles(['status'=>1, 'is_rec'=>1], 5);
        // header
        $this->getHeader(1, new \app\common\model\Nav(), $categoryId);
        //View::assign('cur_location', (new CommonService())->getCurLocation($categoryId));
        View::assign('cur_location', (new CommonService())->getCurPos((new \app\common\model\ArticleCategory()),$categoryId));
        View::assign('child_nav', $childNav);
        View::assign('category_id', $categoryId);
        View::assign('data', $items);
        View::assign('rec_news', $recNews);
        return View::fetch();
    }

    /**
     * 文章详情
     * @param $id
     * @return void
     */
    public function detail($id, $categoryId = 0)
    {
        $service = new ArticleService();
        $item = $service->getArticleDetail($id);
        if (empty($item)) {
            return View::fetch('404.html');
        }
        // 上一篇
        $prevArticle = $service->getPrevArticle($id, $categoryId);
        // 下一篇
        $nextArticle = $service->getNextArticle($id, $categoryId);
        // 新闻推荐
        $recArticles = $service->getRecArticles(['status'=>1, 'is_rec'=>1], 5);
        // header
        $this->getHeader(1, new \app\common\model\Article(), $item->category_id, $id);
        View::assign('cur_location', (new CommonService())->getCurPos(new \app\common\model\Article(), $item->category_id, $id));
        View::assign('data', $item);
        View::assign('rec_news', $recArticles);
        View::assign('prev', $prevArticle);
        View::assign('next', $nextArticle);
        // 更新浏览量
        $service->views($id);
        return View::fetch();
    }
}